' Copyright (c) Microsoft Corporation.  All rights reserved.
Imports System
Imports System.Collections.Generic
Imports System.Data.Metadata.Edm
Imports System.Linq
Imports System.Runtime.CompilerServices

Namespace EdmMetadataHelpersVB
    ''' <summary>
    ''' A number of extension properties that extend the behavior of System.Data.Metadata.Edm.MetadataItems
    ''' </summary>
    <Extension()> _
    Public Module MetadataItemExtensions
        ''' <summary>
        ''' Get hold of a dictionary named attributes that you want to attach to Metadata items
        ''' </summary>
        <Extension()> _
        Public Function GetExtendedProperties(ByVal obj As MetadataItem) As Dictionary(Of String, Object)
            If Not MetadataItemExtensions._extensions.Keys.Contains(obj) Then
                MetadataItemExtensions._extensions.Add(obj, New Dictionary(Of String, Object))
            End If
            Return MetadataItemExtensions._extensions.Item(obj)
        End Function
        ''' <summary>
        ''' Works out whether an EdmProperty is also a Key.
        ''' </summary>
        Friend Function GetIsEntityKey(ByVal [property] As EdmProperty) As Boolean
            Dim IsEntityKey As Boolean = False
            Dim et As EntityType = TryCast([property].DeclaringType, EntityType)
            If (Not et Is Nothing) Then
                IsEntityKey = et.KeyMembers.Any(Function(km) km.Name = [property].Name)
            End If
            Return IsEntityKey
        End Function
        ''' <summary>
        ''' Works out whether an EdmProperty is also a Key. Uses a Cache.
        ''' </summary>
        <Extension()> _
        Public Function IsEntityKey(ByVal [property] As EdmProperty) As Boolean
            Dim extensions As Dictionary(Of String, Object) = [property].GetExtendedProperties()
            If Not extensions.ContainsKey("IsEntityKey") Then
                extensions.Item("IsEntityKey") = MetadataItemExtensions.GetIsEntityKey([property])
            End If
            Return CBool(extensions.Item("IsEntityKey"))
        End Function
        ''' <summary>
        ''' A cache of extended properties
        ''' </summary>
        Private _extensions As Dictionary(Of MetadataItem, Dictionary(Of String, Object)) = New Dictionary(Of MetadataItem, Dictionary(Of String, Object))
    End Module
End Namespace

